package socket.socketByNIO.client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Scanner;

/**
 * Created by yanglh on 2017/11/5.
 */
public class NClient {
    //用于检测所有channel的多路复用器
    private Selector selector = null;
    static final int PORT = 30000;
    //定义实现编码、解码的字符集对象
    private Charset charset = Charset.forName("UTF-8");
    //客户端SocketChannel
    private SocketChannel sc = null;

    public void init() throws IOException {
        selector = Selector.open();
        InetSocketAddress isa = new InetSocketAddress("127.0.0.1",PORT);
        //将该ServerSocketChannel绑定到指定IP地址
        sc = SocketChannel.open(isa);
        //设置该sc以非阻塞方式工作
        sc.configureBlocking(false);
        //将SocketChannel对象注册到指定的Selector
        sc.register(selector, SelectionKey.OP_READ);
        //启动读取服务器端数据的线程
        new ClientThread().start();
        Scanner scan = new Scanner(System.in);
        while (scan.hasNextLine()){
            //读取键盘输入
            String line = scan.nextLine();
            //将键盘输入的内容输出到SocketChannel
            sc.write(charset.encode(line));
        }
    }

    //定义读取服务器端数据的线程
    public class ClientThread extends Thread{
        public void run(){
            try {
                while (selector.select()>0){
                    //遍历每个有可用IO操作的Channel对应的SelectionKey
                    for(SelectionKey sk : selector.selectedKeys()){
                        //删除正在处理的SelectionKey
                        selector.selectedKeys().remove(sk);
                        //如果该SelectionKey对应的channel中有可读的数据
                        if(sk.isReadable()){
                           SocketChannel sc = (SocketChannel)sk.channel();
                            ByteBuffer buff = ByteBuffer.allocate(1024);
                            String content = "";
                            while (sc.read(buff)>0){
                                sc.read(buff);
                                buff.flip();
                                content += charset.decode(buff);
                            }
                            System.out.println("聊天信息："+content);
                            //将sk对应的Channel重置成准备下一次读取
                            sk.interestOps(SelectionKey.OP_READ);
                        }
                    }
                }
            }catch (IOException ex){
                ex.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        try {
            new NClient().init();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}